package com.zh.note.demo.javaSE;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author: zhanghuan
 * @date: 2025/8/24 00:04
 * @description: create it
 * 深拷贝与浅拷贝
 */
public class ShallowDeepCopyDemo implements Cloneable {
    public static void main(String[] args) throws CloneNotSupportedException {
        // ShallowDeepCopyDemo shallowDeepCopyDemo = new ShallowDeepCopyDemo();
        // Object clone = shallowDeepCopyDemo.clone();
        // System.out.println(clone.hashCode());
        m1();
    }

    private static void m1() throws CloneNotSupportedException {
        Employee employee = new Employee("zhangsan", 19, "雷军", "CEO");
        System.out.println("原始对象" + employee.getBoss().getTitle());

        Employee employee2 = (Employee) employee.clone();
        System.out.println("拷贝对象" + employee2.getBoss().getTitle());
        System.out.println("-------------------");
        employee2.getBoss().setTitle("CTO");

        System.out.println("原始对象" + employee.getBoss().getTitle());
        System.out.println("拷贝对象" + employee2.getBoss().getTitle());
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class Boss implements Cloneable {
        private String bossName;
        private String title;

        @Override
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class Employee implements Cloneable {
        private String employeeName;
        private Integer age;
        private Boss boss;

        public Employee(String employeeName, Integer age, String bossName, String title) {
            this.employeeName = employeeName;
            this.age = age;
            this.boss = new Boss(bossName, title);
        }

        /**
         * 浅拷贝
         */
        // @Override
        // protected Object clone() throws CloneNotSupportedException {
        //     return super.clone();
        // }


        /**
         * 深拷贝
         */
        @Override
        protected Object clone() throws CloneNotSupportedException {
            return new Employee(employeeName, age, boss.getBossName(), boss.getTitle());
        }
    }
}
